package de.homelabs.hlmodules.cms.realm.service;

import java.io.File;
import java.io.FileFilter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import de.homelabs.hlmodules.cms.configuration.service.HLConfigurationManager;

/**
 * TODO: provide different strategies
 * @author dmueller
 *
 */
@Service("hlRealmService")
public class HLRealmService {

	@Autowired
	@Qualifier("hlConfigurationManager")
	HLConfigurationManager hlConfigurationManager;
	
	public String getNormalizedDomain(HttpServletRequest request){
		String serverName = request.getServerName();
		//cut www
		if (serverName != null)
			serverName = serverName.replace("www.", "");
		return serverName;
	}
	
	public boolean isDomainSupported(HttpServletRequest request){
		String serverName = getNormalizedDomain(request);
		if (serverName != null){
			// This filter only returns directories
			FileFilter fileFilter = new FileFilter() {
			    public boolean accept(File file) {
			        return file.isDirectory();
			    }
			};
				
			File baseDir = new File(hlConfigurationManager.getConfigurationByDomain(this.getNormalizedDomain(request)).getConfigPath());
			File[] subdirs = baseDir.listFiles(fileFilter);
			for(File testDir : subdirs){
				if (testDir.getName().equalsIgnoreCase(serverName)){
					return true;
				}
			}
		}
		
		return false;
	}
}
